import axios from 'axios'
import { API_BASE_URL } from '../config/api'

// 获取用户树接口
export function getUserTree(params) {
  const formData = new URLSearchParams()
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== '') {
      formData.append(key, value)
    }
  })
  return axios.post(`${API_BASE_URL}/actions/userManageUrl/getUserTree`, formData, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })
}

// 保存/修改用户接口
export function saveOrUpdateUser(userDTO) {
  return axios.post(`${API_BASE_URL}/actions/userManageUrl/saveOrUpdateUser`, userDTO, {
    headers: { 'Content-Type': 'application/json' }
  })
}

// 获取所有角色（不分页）
export function getAllRoles() {
  const formData = new URLSearchParams()
  formData.append('pageNum', 1)
  formData.append('pageSize', 9999)
  return axios.post(`${API_BASE_URL}/actions/role/list`, formData, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })
}

// 分配角色接口
export function allocateRole({ userId, roleIds }) {
  const formData = new URLSearchParams()
  formData.append('userId', userId)
  formData.append('roleIds', roleIds)
  return axios.post(`${API_BASE_URL}/actions/userManageUrl/allocateRole`, formData, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })
}

// 获取用户已分配角色
export function getUserRolesByUserId(userId) {
  const formData = new URLSearchParams()
  formData.append('userId', userId)
  return axios.post(`${API_BASE_URL}/actions/userManageUrl/getRoleByRole`, formData, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })
}

// 分配用户到部门
export function setUserDepartment({ userId, departMentId }) {
  const formData = new URLSearchParams()
  formData.append('userId', userId)
  formData.append('departMentId', departMentId)
  return axios.post(`${API_BASE_URL}/actions/userManageUrl/setDepartment`, formData, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  }).catch(err=>{
    console.log(err)
  })
}
